package com.iot.service;

import com.iot.core.JsonHelper;
import com.iot.mapper.*;
import com.iot.mqtt.MQCommon;
import com.iot.mqtt.OpenCommand;
import com.iot.mqtt.Server;
import com.iot.pojo.*;
import com.iot.util.Common;
import com.iot.util.YT;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class Tdecive_handleServiceImpl implements Tdecive_handleService {
    @Autowired
    private Tnb_dev_reqMapper reqMapper;
    @Autowired
    private TdeviceMapper tdeviceMapper;
    @Autowired
    private Tline_emp_setService tline_emp_setService;
    @Autowired
    private Twarn_recordMapper twarn_recordMapper;
    @Autowired
    private Tnb_dev_jsonService tnb_dev_jsonService;
    @Autowired
    private Tnb_dev_up_dataService tnb_dev_up_dataService;
    @Autowired
    private Tnb_dev_down_dataService tnb_dev_down_dataService;
    @Autowired
    private Tnb_dev_reqService tnb_dev_reqService;
    @Autowired
    private Tnb_dev_down_commandService tnb_dev_down_commandService;
    @Autowired
    private Twarn_typeService twarn_typeService;
    @Autowired
    private Tnb_errorMapper tnb_errorMapper;
    @Autowired
    private Tdevice_recordService tdevice_recordService;
    @Autowired
    private DTline_emp_setMapper dTline_emp_setMapper;
    @Autowired
    private com.iot.mapper.Tdevice_statusMapper Tdevice_statusMapper;
    @Autowired
    private Tdevice_signalMapper tdevice_signalMapper;
    @Autowired
    private Tdevice_imageMapper tdevice_imageMapper;
    @Autowired
    private Twarn_record_detailMapper twarn_record_detailMapper;

    @Override
    public void open(int userId, int empId, String imei, int door, String type) throws Exception {
        //判断是否管理管理设备

        MTdevice mTdevice = tline_emp_setService.getUserByImei(empId, imei);
        Date dt = new Date();
        if (mTdevice != null) {
            boolean open = tline_emp_setService.isOpen(empId, mTdevice.getDEVICE_ID(), type);
            if (!open) {
                throw new Exception("没有开锁权限！");
            }
            OpenCommand c = MQCommon.subscribeInfo.get(imei);
            if (c != null) {
                MTnb_dev_req dev_req = reqMapper.singleByWhere(" AND IMEI='" + imei + "' ORDER BY MESSAGETIME DESC");
                if (dev_req != null) {
                    boolean res = Common.getFiveMinutesDiff(dev_req.getMESSAGETIME(), dt);
                    if (res) {
                        throw new Exception("两分钟之内不能重复发送");
                    }
                }
            }
            MTnb_dev_req bean = new MTnb_dev_req();
            bean.setIMEI(imei);
            bean.setMESSAGETIME(dt);
            bean.setDOOR(door);
            bean.setUSER_ID(userId);
            bean.setTYPE(type);
            bean.setEMP_ID(empId);
            reqMapper.insert(bean);
            if (!type.equals("b")) {
                //加入请求列表
                OpenCommand command = new OpenCommand();
                command.setIMEI(imei);
                command.setSTATUS(0);
                command.setSDATE(new Date());
                command.setDOOR(door);
                command.setEMP_ID(empId);
                command.setUSER_ID(userId);
                MQCommon.subscribeInfo.put(imei, command);
            }

        } else {
            throw new Exception("不管理此设备，没有权限打开");
        }
    }


    public void saveNbDevData(String str) {

        MTnb_dev_data data = JsonHelper.toBean(str, MTnb_dev_data.class);
        MTnb_dev_json json = new MTnb_dev_json();
        String messageId = data.getMESSAGEID();
        int meanCode = data.getMEANCODE();
        json.setIMEI(data.getIMEI());
        json.setMESSAGEID(messageId);
        json.setMESSAGETIME(data.getMESSAGETIME());
        json.setMEANCODE(data.getMEANCODE());
        json.setJOSNSTR(str);
        try {
            tnb_dev_jsonService.insert(json);
            if (Common.hasValue(data.getIMAGEURL()) && data.getIMAGEURL().startsWith("http://www.aikustore.com")) {
                MTdevice mTdevice = tdeviceMapper.singleByWhere(" AND IMEI='" + data.getIMEI() + "'");
                MTdevice_image image = new MTdevice_image();
                image.setIMEI(data.getIMEI());
                image.setIMAGEURL(data.getIMAGEURL());
                image.setMESSAGETIME(data.getMESSAGETIME());
                image.setDEVICE_ID(mTdevice.getDEVICE_ID());
                //image.setSTR_JSON(str);
                saveImage(image);
            }
            //设备发送命令后返回的信息
            if (messageId.equals("81")) {
                MTnb_dev_down_data down_data = new MTnb_dev_down_data();
                down_data.setMESSAGEID(messageId);
                down_data.setIMEI(data.getIMEI());
                data.setRSPDATA(data.getRSPDATA());
                tnb_dev_down_dataService.insert(down_data);
                //保存网络信号信息
            } else if (messageId.equals("01")) {
                MTdevice mTdevice = tdeviceMapper.singleByWhere(" AND IMEI='" + data.getIMEI() + "'");
                MTdevice_signal signal = new MTdevice_signal();
                signal.setSDATE(data.getMESSAGETIME());
                signal.setIMSI(data.getIMEI());
                signal.setSIGNALPOWER(data.getSIGNALPOWER());
                signal.setSNR(data.getSNR());
                signal.setTXPOWER(data.getTXPOWER());
                signal.setCELLID(data.getCELLID());
                signal.setDEVICE_ID(mTdevice.getDEVICE_ID());
                tdevice_signalMapper.insert(signal);
                mTdevice.setSIGNAL_ID(signal.getSIGNAL_ID());
                tdeviceMapper.update(mTdevice);
            } else if (messageId.equals("00")) {

            } else if (messageId.equals("02")) {
                //设备上报的信息。
                MTnb_dev_up_data up_data = new MTnb_dev_up_data();
                up_data.setIMEI(data.getIMEI());
                up_data.setMESSAGEID(messageId);
                up_data.setMESSAGETIME(data.getMESSAGETIME());
                up_data.setMEANCODE(data.getMEANCODE());
                up_data.setDOORLOCK(data.getDOORLOCK());
                up_data.setSOAKING(data.getSOAKING());
                up_data.setBATTERYLEVEL(data.getBATTERYLEVEL());
                up_data.setTEMPERATURE(data.getTEMPERATURE());
                up_data.setHUMIDITY(data.getHUMIDITY());
                up_data.setQUAKE(data.getQUAKE());
                up_data.setTILT(data.getTILT());
                up_data.setLOCKSTATUS(data.getLOCKSTATUS());
                //tnb_dev_up_dataService.insert(up_data);
//                if (meanCode == 1) {
//                    saveDevOpen(up_data);
//                } else if (meanCode > 1) {
                saveDevWarn(up_data, str);
//                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void saveDevWarn(MTnb_dev_up_data up_data, String jsonStr) {
        try {
            MTdevice mTdevice = tdeviceMapper.singleByWhere(" AND IMEI='" + up_data.getIMEI() + "'");
            int meanCode = up_data.getMEANCODE();
            int dnum = mTdevice.getDOOR_NUM();
            MTwarn_record mTwarn_record = new MTwarn_record();
            mTwarn_record.setSDATE(up_data.getMESSAGETIME());
            mTwarn_record.setDEVICE_ID(mTdevice.getDEVICE_ID());
            MTwarn_type mTwarn_type = twarn_typeService.singleByWhere(" AND MEANCODE='" + meanCode + "'");
            mTwarn_record.setWARN_TYPE_ID(mTwarn_type.getWARN_TYPE_ID());
            String doors = YT.decimalToBinary(up_data.getDOORLOCK());
            String desc = mTwarn_type.getSNAME() + " ";
            String descDoor = " ";
            if (meanCode == 2) {
                for (int i = 0; i < dnum; i++) {
                    char ch = doors.charAt(i);
                    if (ch == '1') {
                        descDoor += (i + 1) + "号门异常打开 ";
                    }
                }
                desc += descDoor;
            } else if (meanCode == 1) {
                for (int i = 0; i < dnum; i++) {
                    char ch = doors.charAt(i);
                    if (ch == '1') {
                        descDoor += (i + 1) + "号门被打开 ";
                    }
                }
                desc += descDoor;
            } else if (meanCode == 0) {
                for (int i = 0; i < dnum; i++) {
                    char ch = doors.charAt(i);
                    if (ch == '1') {
                        descDoor += (i + 1) + "号门被打开 ";
                    } else {
                        descDoor += (i + 1) + "号门关闭 ";
                    }
                }
                desc += descDoor;
            }

            String desc2 = (up_data.getSOAKING() == 1 ? "进水" : "没有进水") + " 电量：" + up_data.getBATTERYLEVEL() + " 温度 ：" + up_data.getTEMPERATURE() +
                    " 湿度:" + up_data.getHUMIDITY() + " 震动值:" + up_data.getSOAKING() + " 倾斜值:" + up_data.getTILT() + " 电磁锁状态 " + (up_data.getLOCKSTATUS() ==
                    1 ? "锁开" : "锁关");
            mTwarn_record.setDESCS(desc + " " + desc2);
            mTwarn_record.setWARN_LEVEL_ID(1);
            mTwarn_record.setMESSAGEID(up_data.getMESSAGEID());
            mTwarn_record.setJSONSTR(jsonStr);
            twarn_recordMapper.insert(mTwarn_record);
            saveWarnDetail(mTwarn_record, meanCode);


//            if (up_data.getMEANCODE() > 1) {
            Server server = new Server();
            List<MTusers> tusers = dTline_emp_setMapper.getUserByImei(up_data.getIMEI());
            if (tusers.size() > 0) {
                // PUB_用户ID_DATA
                for (MTusers user : tusers) {
                    MTnb_pub_user_data data = new MTnb_pub_user_data();
                    data.setIMEI(up_data.getIMEI());
                    data.setERRCODE(up_data.getMEANCODE());
                    data.setMESSAGEID(up_data.getMESSAGEID());
                    data.setWARN_ID(mTwarn_record.getWARN_ID());
                    server.publish("PUB_" + user.getUSERS_ID() + "_DATA", JsonHelper.toJson(data), 1);
                }
            }
//            }
        } catch (MqttException e) {
            e.printStackTrace();
        }


    }

    public void saveWarnDetail(MTwarn_record mTwarn_record, int meanCode) {
        Map<String, String> sensor = new HashMap<>();
        //sensor_id-warn_type_id
        sensor.put("doorLock", "1-5");//门磁信息不写入子表
        sensor.put("soaking", "2-2");
        sensor.put("batteryLevel", "3-6");
        sensor.put("temperature", "4-1");
        sensor.put("humidity", "5-9");
        sensor.put("quake", "19-23");
        sensor.put("tilt", "6-4");
        sensor.put("lockStatus", "7-8");
        int doorNor = 11;
        int doorNum = 0;
        int sensorId = 0;
        int warnTypeId = 0;
        //if (meanCode == 0 || meanCode > 1) {
        Map<String, Object> map = JsonHelper.toMap(mTwarn_record.getJSONSTR());
        for (String key : sensor.keySet()) {
            Object val = map.get(key);
            String[] sw = sensor.get(key).split("-");
            sensorId = Common.toInt(sw[0]);
            warnTypeId = Common.toInt(sw[1]);
            MTwarn_record_detail m = new MTwarn_record_detail();

            m.setWARN_RECORD_ID(mTwarn_record.getWARN_ID());
            m.setDEVICE_ID(mTwarn_record.getDEVICE_ID());
            m.setSENSOR_ID(sensorId);
            if (meanCode == 0) {
                m.setSTATUS("0");
            } else {
                m.setWARN_TYPE_ID(warnTypeId);
                m.setSTATUS("1");
            }
            m.setVAL(val + "");
            twarn_record_detailMapper.insert(m);
        }
        // }

    }

    public void saveDevOpen(MTnb_dev_up_data up_data) {
        MTdevice mTdevice = tdeviceMapper.singleByWhere(" AND IMEI='" + up_data.getIMEI() + "'");
        int dnum = mTdevice.getDOOR_NUM();
        MTdevice_record record = new MTdevice_record();
        record.setSDATE(up_data.getMESSAGETIME());
        record.setDEVICE_ID(mTdevice.getDEVICE_ID());
        MTdevice_status status = Tdevice_statusMapper.singleByWhere(" AND SNAME='打开'");
        record.setSTATUS_ID(status.getSTATUS_ID());
        //record.setDESCS("门被打开");
        String desc = "";
        //record.setWARN_LEVEL_ID(1);
        // record.setMESSAGEID(up_data.getMESSAGEID());
        try {
            String doors = YT.decimalToBinary(up_data.getDOORLOCK());
            for (int i = 0; i < dnum; i++) {
                char ch = doors.charAt(i);
                if (ch == '1') {
                    desc += (i + 1) + "号门被打开 ";
                    //  record.setDOOR(i + 1);
                }
            }
            record.setDESCS(desc);
            tdevice_recordService.insert(record);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //  }
    }

    @Override
    public void saveDownCommand(MTnb_dev_down_command down_command) {
        try {
            tnb_dev_down_commandService.insert(down_command);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void insertError(MTnb_error bean) {
        tnb_errorMapper.insert(bean);
    }

    @Override
    public void getUpData() {

    }


    public MTnb_dev_req getLastReq(String imei) {
        MTnb_dev_req mreq = tnb_dev_reqService.singleByWhere(" AND IMEI='" + imei + "' ORDER BY MESSAGETIME DESC");
        return mreq;
    }

    public void saveImage(MTdevice_image image) {
        try {
            tdevice_imageMapper.insert(image);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
